from django.shortcuts import render
from django.http import HttpResponse
from library.models import *
import json
from django.core import serializers

def index(request):
    banners = Banner.objects.all()[:5]
    banners = sorted(banners, key=lambda x:x.weight, reverse=True)
    categories = Category.objects.filter(index_show=1)
    for category in categories:
        category.books = category.book_set.all()
    return_data = {'categories': categories, 'banners': banners}
    return render(request, 'library/index.html', return_data)

def search(request):
    words = request.GET.get('words')
    if words and words.strip():
        books = Book.objects.filter(name__icontains=words)
        books_data = []
        for book in books:
            book_data = {}
            book_data['id'] = book.id
            book_data['name'] = book.name
            book_data['author'] = book.author
            book_data['content_introduction'] = book.content_introduction[:100]
            book_data['cover'] = book.cover.url
            books_data.append(book_data)
        return HttpResponse(json.dumps(books_data))
    return render(request, 'library/search.html')

def book_detail(request, id):
    book = Book.objects.get(id=id)
    return_data = {'book': book}
    return render(request, 'library/book_detail.html', return_data)

def classification(request):
    top_categories = Category.objects.filter(level=1)
    sub_categories = []
    for catogory in top_categories:
        sub_categories.append(Category.objects.filter(top_level=catogory.id))
    return_data = {'top_categories': top_categories, 'sub_categories': sub_categories}
    return render(request, 'library/classification.html', return_data)

def class_books(request, id):
    category = Category.objects.get(id=id)
    books = category.book_set.all()
    return_data = {'category': category, 'books': books}
    return render(request, 'library/class_books.html', return_data)
